package com.harmonyos.cases.utils;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.harmonyos.cases.action.DemoTestAction;
import com.harmonyos.cases.constants.Constants;
import com.harmonyos.cases.view.PluginDialog;
import org.apache.http.client.methods.HttpGet;

import java.io.File;
import java.io.IOException;

// 下载代码
public class GiteeApiClient {
    // 文件总数
    private final int fakeCount = 30;
    // 文件下载数量
    private int initCount = 0;
    // gif路径
    private String gifPath;

    public GiteeApiClient() {

    }

    public void setGifPath(String gifPath) {
        this.gifPath = gifPath;
    }

    /**
     * 获取指定仓库中所有文件的 Raw URLs
     *
     * @param subPath 路径信息
     * @throws IOException
     * @throws InterruptedException
     */
    public void getAllFileRawUrls(String subPath, String localPath, String rootPath) throws IOException, InterruptedException {
        String path = ""; // 从根目录开始
        updateProgress("0%");
        // 递归遍历gitee仓中的所有文件
        fetchFilesRecursively(subPath, path, localPath);
        // 如果实际文件数少于总文件数，则最后显示99%
        if (DemoTestAction.canDownload) {
            Thread.sleep(1000);
            updateProgress("99%");
        }
        // 自定义装饰器案例特殊处理，需要额外下载ts插件
        if (subPath.equals("CommonAppDevelopment/feature/customdecoration/")) {
            String libPath = "https://gitee.com/harmonyos-cases/cases/raw/master/CommonAppDevelopment/libs/autobuilddecoration-1.0.2.tgz";
            File file = new File(rootPath + "/" + "libs");
            if (!file.exists()) {
                file.mkdirs();
            }
            HttpRequest.getInstance().download(libPath, rootPath + "/" + "libs/autobuilddecoration-1.0.2.tgz");
        }
    }
    // 遍历gitee仓里所有文件
    private void fetchFilesRecursively(String subPath, String path, String localPath) throws IOException {
        String homePath = Constants.HOME_URL + "/" + subPath + "/" + path;
        // 如果下载中断，则直接return
        if (!DemoTestAction.canDownload) {
            return;
        }
        // 请求仓库文件数据
        String result = HttpRequest.getInstance().executeGet(new HttpGet(homePath + Constants.TEST_ACCESS_TOKEN + PluginDialog.localRef));
        if (result == null) {
            return;
        }
        // 解析返回结果
        JsonElement jsonElement = JsonParser.parseString(result);
        if (jsonElement.isJsonArray()) {
            JsonArray jsonArray = jsonElement.getAsJsonArray();
            for (JsonElement element : jsonArray) {
                JsonObject obj = element.getAsJsonObject();
                String type = obj.get("type").getAsString();
                String filePath = obj.get("path").getAsString();
                // 如果文件类型是file，则执行下载，否则继续遍历文件夹下面的文件
                if ("file".equals(type)) {
                    String downloadUrl = obj.get("download_url").getAsString();
                    File temp = new File(localPath);
                    if (!temp.exists()) {
                        temp.mkdirs();
                    }
                    // 下载文件
                    HttpRequest.getInstance().download(downloadUrl, localPath + "/" + obj.get("name").getAsString(), gifPath);
                    // 计算文件下载数量
                    initCount = initCount + 1;
                    int progress = initCount * 100 / fakeCount;
                    // 如果进度大于99%，则保持在99%
                    if (progress >= 99) {
                        progress = 99;
                    }
                    // 更新进度条进度
                    updateProgress(progress + "%");
                } else if ("dir".equals(type)) {
                    // 递归处理子目录
                    fetchFilesRecursively(subPath + "/" + path, obj.get("name").getAsString(), localPath + "/" + obj.get("name").getAsString());
                }
            }
        } else if (jsonElement.isJsonObject()) {
            // 单个文件或目录
            JsonObject obj = jsonElement.getAsJsonObject();
            String type = obj.get("type").getAsString();
            String filePath = obj.get("path").getAsString();
            if ("file".equals(type)) {
                String downloadUrl = obj.get("download_url").getAsString();
                HttpRequest.getInstance().download(downloadUrl, localPath + filePath, gifPath);
                initCount = initCount + 1;
                int progress = initCount * 100 / fakeCount;
                if (progress >= 99) {
                    progress = 99;
                }
                updateProgress(progress + "%");
            } else if ("dir".equals(type)) {
                // 递归处理子目录
                fetchFilesRecursively(subPath + "/" + path, obj.get("name").getAsString(), localPath);
            }
        }

    }
    // 更新进度条进度
    private void updateProgress(String progress) {
        if (DemoTestAction.progressWindow != null) {
            DemoTestAction.progressWindow.setText2(String.format("下载中...%s", progress));
        }
    }
}
